package org.store.domain;

import org.codehaus.jackson.annotate.JsonIgnore;

import javax.xml.bind.annotation.XmlTransient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Category extends Identified {
    private final List<Category> subcategories = new ArrayList<Category>();

    @JsonIgnore
    private Category parent;

    private String name;
    private Long parentId;

    public String getName() {
        return name;
    }

    public Long getParentId() {
        return parentId;
    }

    public Category(String name, Long parentId) {
        this.name = name;
        this.parentId = parentId;
    }

    public Category() {
    }

    public Category(Long id) {
        this.id = id;
    }

    public void addChild(Category category) {
        if (category == null) {
            throw new IllegalArgumentException("Cannot be null");
        }

        Category parent = category.getParent();
        if (parent != null) {
            parent.removerChild(category);
        }

        category.setParent(this);
        subcategories.add(category);
    }

    public boolean isA(Category category) {
        return equals(category) || (parent != null && parent.isA(category));
    }

    private void removerChild(Category categoty) {
        subcategories.remove(categoty);
    }

    @JsonIgnore
    public Category getParent() {
        return parent;
    }

    public Category setParent(Category parent) {
        this.parent = parent;
        return this;
    }

    public List<Category> getSubcategories() {
        return subcategories;
    }

    protected Map<Long, Category> saveCategoryToMap(List<Category> categories) {
            if (categories.isEmpty())
                throw new IllegalArgumentException("Lst of categories is Empty");

            Map<Long, Category> categoryMap = new HashMap<>();
            for (Category category : categories) {
                categoryMap.put(category.getId(), category);
            }
            return categoryMap;
        }


}
